<form class="layui-form" action="" lay-filter="admin">
    <input type="hidden" id="userId" th:value="${userId}"/>
    <table id="demo" class="layui-hide" lay-filter="adminInfo"></table>
</form>
<!--用于序号列 递增，（但表头type: 'numbers'也可以）-->
<script type="text/html" id="num">
    {{d.LAY_TABLE_INDEX+1}}
</script>
<script type="text/html" id="barDemo">
    {{#  if(d.id != $("#userId").val()){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{#  } }}
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <!--注意：上面使用的表单，内部的其他按钮 不要使用button-->

    </div>
</script>
<script type="text/html" id="accessToken">
    {{#  if(d.failure == true){ }}
    <span  style="background-color:red" >{{d.accessToken}}</span>
    {{#  } else { }}
    <span>{{d.accessToken}}</span>
    {{#  } }}
</script>
<script th:inline="javascript">
    /*<![CDATA[*/
    layui.use(['table','form','layer'], function () {
        let form = layui.form,
            table = layui.table,
            layer = layui.layer;
        let refreshs = true;
        let temp ={};
        //第一个实例
        let tableInit = table.render({
            elem: '#demo'
            , height: 'full-160' //高度最大化减去差值
            , url: '/admin/allUserInfo' //数据接口
            , toolbar: '#toolbarDemo' //指向自定义工具栏模板选择器 并开启自带工具
            , method : 'get' // http请求类型 默认get
            , contentType: 'application/x-www-form-urlencoded'
            , response : {
                /*
                    默认规定的数据格式为
                    {
                      "code": 0,
                      "msg": "",
                      "count": 1000,
                      "data": [{}, {}]
                    }
                    现在借助response 重新规定返回的数据格式
                */
                statusName : 'code'
                , statusCode : 1
            }
            , done: function (res, curr, count) { /* 表格自适应 */
                $("table").css("width", "100%");
            }, parseData: function(res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.rows //解析数据列表
                };
            }
            , cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                , {title: '序号',type: 'numbers', width: 80, sort: true, fixed: 'left'}
                , {field: 'nickname', title: '昵称'}
                , {field: 'account', title: '账号'}
                , {field: 'roleNames', title: '角色'}
                , {fixed: 'right', title:'操作', width:120,toolbar: '#barDemo'}
            ]]
            , page: true //开启分页
        });




        //头工具栏事件
        table.on('toolbar(pddBuyerInfo)', function(obj){
            switch(obj.event){
                case 'addPddBuyer':
                    layer.open({
                        type: 2,//2（iframe层）
                        title: "添加买家",
                        scrollbar: false,
                        area:[($(window).width() - 50)+'px', ($(window).height() - 50) +'px'],
                        content: "/pdd/addPddBuyerView",
                        end: function () {
                            tableInit.reload();
                        }
                    });
                    break;
                case 'upReceive':
                    let data = table.checkStatus(obj.config.id).data;
                    if(data.length === 0){
                        layer.msg('请选择账户',{
                            icon: 2
                        });
                    } else {
                        let phones =[];
                        for (const datum of data) {
                            phones.push(datum.phone)
                        }
                        $.ajax({
                            type: 'POST',
                            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                            url: "/pdd/batchUpdateReceive",
                            data: {phones:phones.toString(),receive:1},
                            success: function(result){
                                if(result.code === 1){
                                    layer.msg('开启自动收货');
                                    tableInit.reload();
                                }else {
                                    layer.msg('修改失败', {icon: 2,time: 1200});
                                }
                            },
                            error : function(e){
                                layer.msg('网络错误', {icon: 2});
                            }
                        });
                    }
                    break;
                case 'downReceive':
                    let data1 = table.checkStatus(obj.config.id).data;
                    if(data1.length === 0){
                        layer.msg('请选择账户',{
                            icon: 2
                        });
                    } else {
                        let phones =[];
                        for (const datum of data1) {
                            phones.push(datum.phone)
                        }
                        $.ajax({
                            type: 'POST',
                            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                            url: "/pdd/batchUpdateReceive",
                            data: {phones:phones.toString(),receive:0},
                            success: function(result){
                                if(result.code === 1){
                                    layer.msg('关闭自动收货');
                                    tableInit.reload();
                                }else {
                                    layer.msg('修改失败', {icon: 2,time: 1200});
                                }
                            },
                            error : function(e){
                                layer.msg('网络错误', {icon: 2});
                            }
                        });
                    }
                    break;
                case 'enabling':
                    let data2 = table.checkStatus(obj.config.id).data;
                    if(data2.length === 0){
                        layer.msg('请选择账户',{
                            icon: 2
                        });
                    } else {
                        let ids =[];
                        for (const datum of data2) {
                            ids.push(datum.id)
                        }
                        $.ajax({
                            type: 'POST',
                            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                            url: "/pdd/batchUpdateEnabled",
                            data: {ids:ids.toString(),enabled:1},
                            success: function(result){
                                if(result.code === 1){
                                    layer.msg('启用账户');
                                    tableInit.reload();
                                }else {
                                    layer.msg('修改失败', {icon: 2,time: 1200});
                                }
                            },
                            error : function(e){
                                layer.msg('网络错误', {icon: 2});
                            }
                        });
                    }
                    break;
                case 'enabled':
                    let data3 = table.checkStatus(obj.config.id).data;
                    if(data3.length === 0){
                        layer.msg('请选择账户',{
                            icon: 2
                        });
                    } else {
                        let ids =[];
                        for (const datum of data3) {
                            ids.push(datum.id)
                        }
                        $.ajax({
                            type: 'POST',
                            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                            url: "/pdd/batchUpdateEnabled",
                            data: {ids:ids.toString(),enabled:0},
                            success: function(result){
                                if(result.code === 1){
                                    layer.msg('禁用账户');
                                    tableInit.reload();
                                }else {
                                    layer.msg('修改失败', {icon: 2,time: 1200});
                                }
                            },
                            error : function(e){
                                layer.msg('网络错误', {icon: 2});
                            }
                        });
                    }
                    break;
                case 'refresh':
                    refresh();
                    break;
            }
        });

        //监听行工具事件
        table.on('tool(adminInfo)', function(obj){
            let data = obj.data;
            console.log(data);
            if(obj.event === 'del'){
                layer.confirm('&emsp;&emsp;&emsp;&emsp;真的删除这行么？</br>此次操作，将会删除此账号的一切相关信息', function(index){
                    $.ajax({
                        type: 'POST',
                        contentType: 'application/json;charset=UTF-8',
                        url: "/admin/deleteUser",
                        data: JSON.stringify(data),
                        success: function(result){
                            if(result.code === 1){
                                obj.del();
                                layer.close(index);
                                layer.msg('删除成功', {icon: 1,time: 1200});
                            }else {
                                layer.msg('删除失败', {icon: 2,time: 1200});
                            }
                        },
                        error : function(e){
                            layer.msg('网络错误', {icon: 2});
                        }
                    });
                });
            } else if(obj.event === 'edit'){
                layer.open({
                    type: 2,//2（iframe层）
                    title: `修改信息`,
                    scrollbar: false,
                    area:[($(window).width() - 50)+'px', ($(window).height() - 50) +'px'],
                    //content: "/dev/getCode/"+data.id+"/"+data.phone,
                    end: function () {
                        tableInit.reload();
                    }
                });
            }
        });
        form.on('switch(enabled)', function(data){
            $.ajax({
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                url: "/pdd/updateEnabled",
                data: {id:data.elem.value,enabled:data.elem.checked},
                success: function(result){
                    if(result.code === 1){
                        let status = data.elem.checked?'启动':'禁用';
                        layer.tips('温馨提示：您已'+status+'此账户', data.othis);
                    }else {
                        layer.msg('修改失败', {icon: 2,time: 1200});
                    }
                },
                error : function(e){
                    layer.msg('网络错误', {icon: 2});
                }
            });

        });
        form.on('switch(receive)', function(data){
            $.ajax({
                type: 'POST',
                contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                url: "/pdd/updateReceive",
                data: {id:data.elem.value,receive:data.elem.checked},
                success: function(result){
                    if(result.code === 1){
                        let status = data.elem.checked?'启动':'禁用';
                        layer.tips('温馨提示：您已'+status+'自动收货', data.othis);
                    }else {
                        layer.msg('修改失败', {icon: 2,time: 1200});
                    }
                },
                error : function(e){
                    layer.msg('网络错误', {icon: 2});
                }
            });

        });


        let refresh =()=>{
            clearInterval(temp.time);
            temp.time =setInterval(function() {
                tableInit.reload();
            },10000);
            if(refreshs === true){
                refreshs = false;
                layer.msg('开启自动刷新');
                $("#refresh").attr("class","layui-btn layui-btn-sm");
            } else {
                refreshs = true;
                clearInterval(temp.time);
                layer.msg('关闭自动刷新');
                $("#refresh").attr("class","layui-btn layui-btn-sm layui-btn-danger");
            }
        }
        /* window.setInterval(function() {
             tableInit.reload();
         },10000);*/
    });
    /*]]>*/
</script>
